const app = getApp()
const db = wx.cloud.database();
const _ = db.command;
//计数器
var interval = null;
var randmArr = [1, 5, 10, 20, 35, 55, 100, 100] //概率 8 格
var obj = { a1: 1, a2: 4, a3: 5, a4: 12, a5: 16, a6: 14, a7: 48, a8: 50 } //产生的随机数的次数
var form = {} //统计中奖的概率
//值越大旋转时间越长  即旋转速度
var intime = 20;
// 插屏广告
let interstitialAd = null;
Page({
  data: {
    openid: '889',
    userInfo: null,
    signNum: 0,
    signTime: '',
    luckNum: 0,

    // 奖项及概率
    jp: [5, 8, 15, 20, 30, 50, 100, 200],
    gl: [26, 23, 20, 16, 8, 4, 2, 1],
    color: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],
    //9张奖品图片
    images: ['/images/item.png', '/images/item1.png', '/images/item.png', '/images/item1.png', '/images/item.png', '/images/item1.png', '/images/item.png', '/images/item1.png', '/images/item.png'],
    btnconfirm: '/images/dianjichoujiang.png',
    clickLuck: 'clickLuck',
    //概率
    // randmArr: [1,5,10,20,35,55,100,100]
    // 中奖位置，0-7 从服务端获取????
    luckPosition: -1,
    luckPoint: 0
  },

  onLoad: function () {
    this.loadAnimation();
    // this.getTaskCount()
    let that = this;
    app.getOpenid(function (result) {
      that.setData({
        openid: result
      })
      app.getUserInfo1(function (result2) {
        that.setData({
          userInfo: result2
        })
      }, result)
      app.getTaskCount(function (result3) {
        console.log(result3)
        that.setData({
          signNum: result3.signNum,
          signTime: result3.signTime,
          luckNum: result3.luckNum
        })
      }, result)
    })
    // 加载慢，测试是注释掉
    that.loadAd();
    
  },

  // 抽奖 写库
  goodluck: function (point) {
    console.log("goodluck=" + point);
    let that = this;
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    let time = app.nowTimeStamp()
    db.collection('ad_point_logs').add({
      data: {
        // "_openid": "",
        type: 2,
        create_time: time,
        point: point,
        week: 1,
        month: 1,
      },
      success: res => {
        // app.addPoint(app.globalData.setting.signPoint);addPoint: function (callBack, openid, point) 
        app.addPoint(function (result) {
          // console.log(result)
        }, that.data.openid, point);
        // wx.hideLoading()
        that.setData({
          luckNum: that.data.luckNum + 1
        })
        // wx.showToast({
        //   title: '抽奖成功',
        //   icon: 'success'
        // })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '抽奖失败',
          icon: 'none'
        })
      }
    })
  },

  input: function (e) {
    var data = e.detail.value;
    this.setData({
      luckPosition: data
    })
  },

  //点击抽奖按钮 渲染
  clickLuck: function () {
    var that = this;
    if (2 - that.data.luckNum <= 0) {
      console.log("抽奖机会用完了！");
      wx.showToast({
        title: '明天再来吧！',
        icon: 'none'
      })
      return;
    } else {
      var luckPosition = that.choujiang();
      var jp = that.data.jp;
      console.log("中奖位置：" + luckPosition + "；奖品：" + jp[luckPosition])
      //设置按钮不可点击
      that.setData({
        luckPosition: luckPosition,
        luckPoint:jp[luckPosition],
        btnconfirm: '/images/dianjichoujiangd.png',
        clickLuck: '',
      })
      that.goodluck(jp[luckPosition]);

      //清空计时器
      clearInterval(interval);
      var index = 0;
      // console.log(that.data.color[0]);
      //循环设置每一项的透明度
      interval = setInterval(function () {
        if (index > 7) {
          index = 0;
          that.data.color[7] = 0.5
        } else if (index != 0) {
          that.data.color[index - 1] = 0.5
        }
        that.data.color[index] = 1
        that.setData({
          color: that.data.color,
        })
        index++;
      }, intime);
      //模拟网络请求时间  设为两秒
      var stoptime = 2000;
      setTimeout(function () {
        that.stop(luckPosition);
      }, stoptime)
    }
  },

  // 测试概率
  btn1: function (e) {
    console.log("测试概率=")
    // console.log("测试概率=" + zs);[26, 23, 20, 16, 8, 4, 2, 1],
    var b = [0, 0, 0, 0, 0, 0, 0, 0]
    for (var i = 0; i < 1000; i++) {
      var a = this.choujiang();
      b[a] += 1;
    }
    console.log(b);
  },

  // 根据位置的概率抽出一个位置id
  choujiang() {
    let gl = this.data.gl;
    var zs = 0;// 总数，如1-100
    var qj = new Array(8);// 区间
    for (var i in gl) {
      zs += gl[i];
      qj[i] = zs;
    }
    // console.log(qj)
    var sjs = parseInt(Math.random() * (zs) + 1);// 生成概率内的随机数
    var zjh = -1;// 中奖号
    for (var i in qj) {
      if (i > 0) {
        if (sjs > qj[i - 1] && sjs <= qj[i]) {
          zjh = i;
          break;
        }
      } else {
        if (sjs > 0 && sjs <= qj[i]) {
          zjh = i;
          break;
        }
      }
    }
    return zjh;
  },

  //也可以写成点击按钮停止抽奖
  // clickStop:function(){
  //   var stoptime = 2000;
  //   setTimeout(function () {
  //     e.stop(1);
  //   }, stoptime)
  // },

  stop: function (which) {
    var e = this;
    //清空计数器
    clearInterval(interval);
    //初始化当前位置
    var current = -1;
    var color = e.data.color;
    for (var i = 0; i < color.length; i++) {
      if (color[i] == 1) {
        current = i;
      }
    }
    //下标从1开始
    var index = current + 1;
    e.stopLuck(which, index, intime, 10);
  },

  loadAd() {
    // 插屏广告
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-01d343fb18e483f9' })
      interstitialAd.onLoad(() => {
        console.log('onLoad 插屏广告')
        if (interstitialAd) {
          interstitialAd.show().catch((err) => {
            console.error(err)
          })
        }
      })
      interstitialAd.onError((err) => {
        console.log('onError 插屏广告', err)
      })
      interstitialAd.onClose((res) => {
        console.log('onClose 插屏广告', res)
      })
    }
  },

  /**
   * which:中奖位置
   * index:当前位置
   * time：时间标记
   * splittime：每次增加的时间 值越大减速越快
   */
  stopLuck: function (which, index, time, splittime) {
    var e = this;
    //值越大出现中奖结果后减速时间越长
    var color = e.data.color;
    setTimeout(function () {
      //重置前一个位置
      if (index > 7) {
        index = 0;
        color[7] = 0.5
      } else if (index != 0) {
        color[index - 1] = 0.5
      }
      //当前位置为选中状态
      color[index] = 1
      e.setData({
        color: color,
      })
      //如果旋转时间过短或者当前位置不等于中奖位置则递归执行
      //直到旋转至中奖位置
      if (time < 400 || index != which) {
        //越来越慢
        splittime++;
        time += splittime;
        //当前位置+1
        index++;
        e.stopLuck(which, index, time, splittime);
      } else {
        //1秒后显示弹窗
        setTimeout(function () {
          //中奖
          wx.showModal({
            title: '提示',
            content: '恭喜中奖 +' +e.data.luckPoint + '票',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                //设置按钮可以点击
                e.setData({
                  btnconfirm: '/images/dianjichoujiang.png',
                  clickLuck: 'clickLuck',
                })
                e.loadAnimation();
              }
            }
          })
        }, 1000);
      }
    }, time);
    // console.log(time);
  },
  //进入页面时缓慢切换
  loadAnimation: function () {
    var e = this;
    var index = 0;
    // if (interval == null){
    interval = setInterval(function () {
      if (index > 7) {
        index = 0;
        e.data.color[7] = 0.5
      } else if (index != 0) {
        e.data.color[index - 1] = 0.5
      }
      e.data.color[index] = 1
      e.setData({
        color: e.data.color,
      })
      index++;
    }, 1000);
    // }  
  }
})
